package com.draven.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.draven.common.Result;
import com.draven.entity.Note;
import com.draven.service.NoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * 笔记控制器
 */
@RestController
@RequestMapping("/note")
public class NoteController {

    @Autowired
    private NoteService noteService;

    /**
     * 添加笔记
     */
    @PostMapping("/add")
    public Result<Long> add(
            HttpServletRequest request,
            @RequestBody Note note) {
        Long userId = (Long) request.getAttribute("userId");
        note.setUserId(userId);
        Long id = noteService.add(note);
        return Result.success(id);
    }

    /**
     * 修改笔记
     */
    @PostMapping("/update")
    public Result<Void> update(
            HttpServletRequest request,
            @RequestBody Note note) {
        Long userId = (Long) request.getAttribute("userId");
        note.setUserId(userId);
        noteService.update(note);
        return Result.success();
    }

    /**
     * 删除笔记
     */
    @PostMapping("/delete")
    public Result<Void> delete(
            HttpServletRequest request,
            @NotNull(message = "ID不能为空") @RequestParam Long id) {
        Long userId = (Long) request.getAttribute("userId");
        noteService.delete(id, userId);
        return Result.success();
    }

    /**
     * 获取笔记详情
     */
    @GetMapping("/detail")
    public Result<Note> detail(
            HttpServletRequest request,
            @NotNull(message = "ID不能为空") @RequestParam Long id) {
        Long userId = (Long) request.getAttribute("userId");
        Note detail = noteService.getDetail(id, userId);
        return Result.success(detail);
    }

    /**
     * 分页查询笔记
     */
    @GetMapping("/page")
    public Result<Page<Note>> page(
            HttpServletRequest request,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String tag,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Long userId = (Long) request.getAttribute("userId");
        Page<Note> page = noteService.page(userId, title, category, tag, pageNum, pageSize);
        return Result.success(page);
    }
} 